﻿
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Collections.Generic;
using System.Threading.Tasks;
using WHLRDF.Log;

namespace WHLRDF.Application.BLL
{
    public class CustomExceptionFilter : IExceptionFilter, IAsyncExceptionFilter
    {

        public void OnException(ExceptionContext context)
        {

            if (!context.ExceptionHandled)
            {
                context.HttpContext.Response.StatusCode = 500;
                string msg = context.Exception.Message;
                if (AppHttpContext.IsAjax)
                {
                    context.Result = new JsonResult(AjaxResult.Error(msg, -100));
                }
                else
                {
                    var view = new ViewResult();
                    var controller = new BaseController();
                    view.ViewData = new Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary(controller.ViewData);
                    view.ViewName = "~/Views/Home/Error.cshtml";
                    view.ViewData["Message"] = msg;
                    view.ViewData["Exception"] = context.Exception;
                    view.ViewData["StatusCode"] = context.HttpContext.Response.StatusCode;
                    context.Result = view;
                }

                LogHelper.Error(context.GetType(), context.Exception);

            }

            context.ExceptionHandled = true; //异常已处理了

        }



        public Task OnExceptionAsync(ExceptionContext context)
        {

            OnException(context);

            return Task.CompletedTask;

        }

    }
}